package com.ttloner1.blob;

import com.ttloner1.util.JDBCUtils;
import org.junit.Test;

import java.io.*;
import java.sql.*;

/**
 * @author TTLoner
 * @date 2021/6/22 21:07
 * @description
 */
public class BlobTest {
    //向数据表customers中插入blob类型的字段
    @Test
    public void test1() throws SQLException, FileNotFoundException {
        Connection connection = JDBCUtils.getConnection();
        String sql="insert into customers(name,email,birth,photo)values(?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setObject(1,"彦彦");
        ps.setObject(2,"test@email.com");
        ps.setObject(3,"1997-01-27");
        FileInputStream photo = new FileInputStream(new File("img/四千年.jpg"));
        ps.setBlob(4,photo);
        ps.execute();
    }
    //查询Blob
    @Test
    public void test2() throws SQLException, IOException {
        Connection conn = JDBCUtils.getConnection();
        String sql="select photo from customers where `name`=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,"彦彦");
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            Blob blob = rs.getBlob("photo");
            //将blob保存到本地
            InputStream is = blob.getBinaryStream();
            FileOutputStream os = new FileOutputStream(new File("blob.jpg"));
            byte[] buffer = new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
        }
        JDBCUtils.closeConnection(conn,ps,rs);

    }
}
